package com.deep.flink;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @author sw
 * @create 2023-06-30 11:26
 */
public class Test13 {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);


        SingleOutputStreamOperator<Event> eventStream = env.addSource(new ClickSource())
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event event, long l) {
                                return event.getTimestamp();
                            }
                        }));

        Table clickTable = tableEnv.fromDataStream(eventStream,
                $("username"), $("url"), $("timestamp").as("ts"),
                $("et").rowtime());

        clickTable.printSchema();

        tableEnv.createTemporaryView("clickTable", clickTable);

        Table aggTable = tableEnv.sqlQuery("select username, count(1) as cnt from clickTable group by username ");

        tableEnv.toChangelogStream(aggTable).print("agg");

        env.execute();

    }
}
